import scrapy
import requests
from bid.items import BidItem
from bid.tools import *


class XizangSpider(scrapy.Spider):
    name = 'xizang'
    allowed_domains = ['ggzy.xizang.gov.cn']
    start_urls = ['https://ggzy.xizang.gov.cn/']
    t_lis = [
        ['3541', '工程建设-招标公告','1'],
        ['3542', '工程建设-更正公告','2'],
        ['3543', '工程建设-中标候选人公示','2'],
        ['3544', '工程建设-中标结果公示','3'],
        ['3545', '工程建设-异常公告','2'],
        ['3547', '政府采购-采购公告','1'],
        ['3548', '政府采购-更正公告','2'],
        ['3549', '政府采购-中标结果公告','3'],
    ]
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg = []

    def start_requests(self):
        for lis in self.t_lis:
            for page in range(1, 9999):
                res = requests.post(f'http://ggzy.xizang.gov.cn/search/queryContents_{page}.jhtml',
                                    data={'channelId': lis[0]}, headers=self.headers)
                res.encoding = 'utf-8'
                ls = re.findall('<li>\s*<p onclick="window.open\(\'(.*?)\'\)">(.*?)</p>\s*<p>(.*?)<', res.text, re.S)
                last_page = math.ceil(int(re.findall('\s,count: (.*?)\s',res.text,re.S)[0])/10)
                if page > int(last_page):
                    break
                for l in ls:
                    item = {}
                    item['link'] = 'http://ggzy.xizang.gov.cn' + l[0]
                    item['title'] = re.sub('\s|<.*?>','',l[1])
                    item['time'] = l[2]
                    item['classification'] = '西藏-'+lis[1]
                    item['typ'] = lis[-1]
                    if redis_dupefilter(item) or item['time'].startswith('2021'):
                        self.msg.append(lis)
                        break
                    yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
                if lis in self.msg:
                    print(lis[1], '完成')
                    break
                time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="WordSection1"]|//div[@class="content-text"]')
        item = get_field(dict(item))
        yield item
